<template>
  <div class="app-container">
    <div class="header-bar">
      <el-button
          type="primary"
          icon="ArrowLeft"
          @click="handleBack"
          class="back-btn"
      >
        返回
      </el-button>
      <h2 class="page-title">饮食记录管理</h2>
    </div>

    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <!-- 新增记录按钮 -->
      <el-form-item class="action-button">
        <el-button type="primary" icon="Plus" @click="handleAdd" class="add-btn">
          新增记录
        </el-button>
        <el-button type="info" icon="List" @click="showCalorieDialog = true">常见热量参考</el-button>
      </el-form-item>

      <!-- 食物名称查询 -->
      <el-form-item label="食物名称" prop="foodName">
        <el-input
            v-model="queryParams.foodName"
            placeholder="请输入食物名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <!-- 日期范围查询 -->
      <el-form-item label="记录日期" prop="dateRange">
        <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            value-format="YYYY-MM-DD"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 320px"
            :disabled-date="disabledDate"
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item class="query-actions">
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="dietList">
      <el-table-column label="记录日期" width="180">
        <template #default="scope">
          {{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}
        </template>
      </el-table-column>
      <el-table-column label="食物名称" prop="foodName" align="center"/>
      <el-table-column label="预计卡路里" prop="estimatedCalories" align="center"/>
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 表单弹窗 -->
    <el-dialog :title="title" v-model="open" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="食物名称" prop="foodName">
          <el-input
              v-model="form.foodName"
              placeholder="请输入食物名称"
              clearable
              :maxlength="50"
              show-word-limit
          />
        </el-form-item>

        <el-form-item label="预计卡路里" prop="estimatedCalories">
          <el-input-number
              v-model="form.estimatedCalories"
              :min="1"
              :max="10000"
              :precision="0"
              controls-position="right"
          />
        </el-form-item>

        <el-form-item label="记录日期" prop="recordTime">
          <el-date-picker
              v-model="form.recordTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择记录日期"
              :disabled-date="disabledDate"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 常见热量参考弹窗 -->
    <el-dialog title="常见食物热量参考" v-model="showCalorieDialog" width="80%">
      <el-table :data="commonFoods" height="400" border>
        <el-table-column prop="name" label="食物名称" width="150"/>
        <el-table-column prop="calories" label="热量（大卡/100g）" width="130"/>
        <el-table-column prop="notes" label="注意事项"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { listDiet, addDiet, updateDiet, delDiet, getDiet } from '@/api/healthSys/diet'

const router = useRouter()
const { proxy } = getCurrentInstance()

// 响应式数据
const loading = ref(false)
const open = ref(false)
const title = ref('')
const dietList = ref([])
const total = ref(0)
const showCalorieDialog = ref(false)
const commonFoods = ref([
  { name: '米饭', calories: 116, notes: '建议搭配粗粮食用' },
  { name: '鸡蛋', calories: 155, notes: '建议每日摄入1-2个' },
  { name: '全麦面包', calories: 264, notes: '优选无添加糖版本' },
  { name: '鸡胸肉', calories: 133, notes: '优质蛋白质来源' },
  { name: '牛肉(瘦)', calories: 113, notes: '优质铁元素来源' },
  { name: '三文鱼', calories: 208, notes: '富含Omega-3脂肪酸' },
  { name: '西兰花', calories: 36, notes: '建议焯水后食用' },
  { name: '苹果', calories: 53, notes: '连皮食用营养更佳' },
  { name: '牛奶(全脂)', calories: 64, notes: '乳糖不耐可替换豆浆' },
  { name: '香蕉', calories: 93, notes: '运动后补充优选' },
  { name: '豆腐', calories: 84, notes: '植物蛋白优质来源' },
  { name: '牛油果', calories: 171, notes: '控制每日摄入量' },
  { name: '燕麦片', calories: 379, notes: '优选无糖即食版本' },
  { name: '红薯', calories: 86, notes: '富含膳食纤维' },
  { name: '鸡腿肉', calories: 191, notes: '去皮后热量更低' },
  { name: '鳕鱼', calories: 82, notes: '低脂高蛋白选择' },
  { name: '虾仁', calories: 48, notes: '建议白灼烹饪' },
  { name: '酸奶(无糖)', calories: 72, notes: '优选益生菌配方' },
  { name: '橙子', calories: 47, notes: '维生素C优质来源' },
  { name: '核桃', calories: 654, notes: '每日建议28g以内' },
  { name: '玉米', calories: 112, notes: '优选新鲜玉米' },
  { name: '花生酱', calories: 588, notes: '控制每日摄入量' },
  { name: '黑巧克力(70%)', calories: 598, notes: '适量食用有益健康' },
  { name: '菠菜', calories: 23, notes: '草酸含量较高需焯水' },
  { name: '意面(干)', calories: 158, notes: '控制酱料热量' },
  { name: '鱿鱼', calories: 75, notes: '低胆固醇海鲜选择' },
  { name: '芝士片', calories: 300, notes: '注意钠含量' },
  { name: '草莓', calories: 32, notes: '洗净后去蒂食用' },
  { name: '杏仁', calories: 578, notes: '每日建议20-25颗' },
  { name: '南瓜', calories: 26, notes: 'β-胡萝卜素丰富' },
  { name: '火腿', calories: 130, notes: '注意亚硝酸盐含量' },
  { name: '海带', calories: 17, notes: '碘元素天然来源' }
])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 12,
  foodName: null,
  dateRange: []
})

// 表单数据
const form = reactive({
  dietId: null,
  userId: null,
  foodName: null,
  estimatedCalories: null,
  recordTime: null
})

// 验证规则
const rules = {
  foodName: [{ required: true, message: '请输入食物名称', trigger: 'blur' }],
  estimatedCalories: [{ required: true, message: '请输入预计卡路里', trigger: 'blur' }],
  recordTime: [{ required: true, message: '请选择记录日期', trigger: 'change' }]
}

// 初始化数据
onMounted(() => {
  getList()
})

// 获取数据列表
const getList = async () => {
  try {
    loading.value = true
    const params = {
     ...queryParams,
      foodName: queryParams.foodName,
      beginDate: queryParams.dateRange?.[0],
      endDate: queryParams.dateRange?.[1]
    }

    const res = await listDiet(params)
    dietList.value = res.rows
    total.value = res.total
  } catch (error) {
    proxy.$modal.msgError('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 查询处理
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  proxy.resetForm('queryRef')
  queryParams.dateRange = []
  queryParams.foodName = null
  handleQuery()
}

// 新增记录
const handleAdd = () => {
  resetForm()
  open.value = true
  title.value = '新增饮食记录'
}

// 修改记录
const handleUpdate = async (row) => {
  try {
    resetForm()
    const res = await getDiet(row.dietId)
    Object.assign(form, res.data)
    open.value = true
    title.value = '修改饮食记录'
  } catch (error) {
    proxy.$modal.msgError('数据加载失败')
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await proxy.$refs.formRef.validate()

    const submitData = {...form }
    if (form.dietId) {
      await updateDiet(submitData)
      proxy.$modal.msgSuccess('修改成功')
    } else {
      await addDiet(submitData)
      proxy.$modal.msgSuccess('新增成功')
    }

    open.value = false
    getList()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 删除处理
const handleDelete = async (row) => {
  try {
    await proxy.$modal.confirm(`确认删除 ${proxy.parseTime(row.recordTime)} 的记录？`)
    await delDiet(row.dietId)
    getList()
    proxy.$modal.msgSuccess('删除成功')
  } catch (error) {
    // 取消删除不处理
  }
}

// 重置表单
const resetForm = () => {
  form.dietId = null
  form.foodName = null
  form.estimatedCalories = null
  form.recordTime = null
}

// 取消操作
const cancel = () => {
  open.value = false
  resetForm()
}

const handleBack = () => {
  router.go(-1)
}

// 添加 disabledDate 函数
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}
</script>

<style scoped>
.app-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.header-bar {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 32px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.header-bar:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
}

.back-btn {
  margin-right: 24px;
  padding: 12px 20px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.back-btn:hover {
  transform: translateX(-3px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  letter-spacing: 0.5px;
  background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.el-form {
  margin: 24px 0;
  padding: 32px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.el-form:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
}

.el-form-item {
  margin-bottom: 24px;
}

.action-button {
  margin-bottom: 32px;
}

.add-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #00b09b 0%, #96c93d 100%);
  border: none;
  color: white;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 176, 155, 0.3);
}

.el-table {
  margin-top: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
}

.el-table:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
}

.el-table :deep(th) {
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  font-weight: 600;
  color: #2c3e50;
  padding: 16px 8px;
}

.el-table :deep(td) {
  padding: 16px 8px;
  transition: all 0.3s ease;
}

.el-table :deep(tr:hover td) {
  background-color: #f8f9fa;
}

.el-button--primary {
  color: white;
  background: linear-gradient(135deg, #6bee4a 0%, #428add 100%);
  border: none;
  transition: all 0.3s ease;
}

.el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.el-dialog {
  border-radius: 16px;
  overflow: hidden;
}

.el-dialog__header {
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__body {
  padding: 24px;
}

.el-dialog__footer {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
}

.el-input-number,
.el-date-editor {
  width: 100%;
}

.calorie-table {
  overflow-x: auto;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .header-bar {
    padding: 16px;
  }

  .el-form {
    padding: 20px;
  }

  .el-date-picker {
    width: 100% !important;
  }

  .el-form-item__content {
    flex-wrap: wrap;
  }

  .el-button {
    margin-top: 8px;
    width: 100%;
  }
}
</style>
